﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Simple.Common;
using Simple.Service;
using Simple.ViewModel;
using Simple.Common.EasyUICommon;
using Simple.Service.Enum;
using Simple.Entity.Models;

namespace HBootStrap.Admin.Controllers
{
    public class LoginController : Controller
    {
        private readonly FormsAuthenticationService _loginService;
        private readonly UserActivityService _userActivityService;

        public LoginController(FormsAuthenticationService loginService, UserActivityService userActivityService)
        {
            _loginService = loginService;
            _userActivityService = userActivityService;
        }


        private string _checkValidCode = "CheckValidCode";
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginDto model, string returnUrl)
        {
            Sys_User sys_User;
            UserLoginResults loginResult = _loginService.ValidateCustomer(model.LoginName, model.PassWord, out sys_User);
            switch (loginResult)
            {
                case UserLoginResults.Successful:
                    {
                        //sign in new customer
                        _loginService.SignIn(sys_User,false);

                        //activity log
                        _userActivityService.InsertActivityLog("用户登录", sys_User.LoginNo);

                        if (String.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
                            return RedirectToAction("Index", "Home");

                        return Redirect(returnUrl);
                    }
                case UserLoginResults.CustomerNotExist:
                    ModelState.AddModelError("", "用户名不存在");
                    break;
                case UserLoginResults.Deleted:
                    ModelState.AddModelError("", "用户已经被删除");
                    break;
                case UserLoginResults.NotActive:
                    ModelState.AddModelError("", "用户没有激活");
                    break;
                case UserLoginResults.WrongPassword:
                default:
                    ModelState.AddModelError("", "用户名或密码错误");
                    break;
            }
            return View();
        }

        public ActionResult GetCheckCode()
        {
            string code = SimpleCheckCode.CreateCode(4);
            SimpleCheckCode.CreateImage(code);
            SimpleSessionHelper.SetSession(_checkValidCode, code);
            return View();
        }

        public ActionResult LoginOut()
        {
            _loginService.SignOut();
            return RedirectToAction("Login");
        }

    }

}

